package cfg

import (
	"log"
	"time"

	"gpt-api/framework/cache"

	"github.com/spf13/viper"
)

// NewRedis RedisFromMicroConf create a new redis instance from config file derived by micro-config
// whole config information is split into two files: one in config-map dir and one insecret dir
//
// # redis-A.yaml in config-map dir
// redis-A:
//
//	MaxOpenConn: 10
//	MaxIdleConn: 2
//
// # redis.yaml in secret dir
// redis:
//
//	host: "tcp:canary-abcc-redis-sh-001.drnbcf.0001.apne1.cache.amazonaws.com:6379"
//
// params resourceName refers to "redis-A" above
func NewRedis(resourceName string, opt ...cache.Opt) *cache.RedisClient {
	host := viper.GetString(resourceName + ".host")
	if host == "" {
		log.Panic("load redis config fail, redis Address is empty ")
		return nil
	}

	if maxopen := viper.GetInt(resourceName + ".maxopenconn"); maxopen != 0 {
		opt = append(opt, cache.WithMaxOpenConnections(maxopen))
	}

	if minidle := viper.GetInt(resourceName + ".minidleconn"); minidle != 0 {
		opt = append(opt, cache.WithMinIdleConnections(minidle))
	}

	if database := viper.GetInt(resourceName + ".database"); database != 0 {
		opt = append(opt, cache.WithDatabase(database))
	}

	if idletimeout := viper.GetInt64(resourceName + ".idletimeout"); idletimeout != 0 {
		opt = append(opt, cache.WithIdleTimeout(time.Duration(idletimeout)*time.Second))
	}

	if pwd := viper.GetString(resourceName + ".password"); pwd != "" {
		opt = append(opt, cache.WithPassword(pwd))
	}

	if ssl := viper.GetBool(resourceName + ".ssl"); ssl {
		opt = append(opt, cache.WithSSL(ssl))
	}

	redisCli, err := cache.NewRedisClient(host, opt...)
	if err != nil {
		log.Panicf("init redis fail %s", err)
	}
	return redisCli
}
